package com.code.petapp.util

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.os.Build
import android.util.DisplayMetrics
import android.view.View
import android.view.WindowManager
import androidx.annotation.RequiresApi

object UiUtils {
    /**
     * 获取屏幕高度，适用于 API 29 及以下版本
     */
    private fun getScreenHeightLegacy(context: Context): Int {
        val displayMetrics = DisplayMetrics()
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        @Suppress("DEPRECATION")
        windowManager.defaultDisplay.getMetrics(displayMetrics)
        return displayMetrics.heightPixels
    }

    /**
     * 获取屏幕高度，适用于 API 30 及以上版本
     */
    @RequiresApi(Build.VERSION_CODES.R)
    private fun getScreenHeightApi30AndAbove(context: Context): Int {
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val windowMetrics = windowManager.currentWindowMetrics
        return windowMetrics.bounds.height()
    }

    /**
     * 根据当前设备的API级别获取屏幕高度
     */
    fun getScreenHeight(context: Context): Int {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            getScreenHeightApi30AndAbove(context)
        } else {
            getScreenHeightLegacy(context)
        }
    }

    fun getScreenShot(view: View): Bitmap {
        val bitmap = Bitmap.createBitmap(
            view.width,
            view.height, Bitmap.Config.ARGB_8888
        )
        val canvas = Canvas(bitmap)
        view.draw(canvas)
        return bitmap
    }
}